package com.github.boluo1230.wechat.dao.impl;

import com.github.boluo1230.wechat.base.config.MongoUtil;
import com.github.boluo1230.wechat.dao.AutoReplyKeywordsInfoDao;
import com.github.boluo1230.wechat.entity.AutoReplyKeywordsInfo;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Code Farmer
 * @date 2019/10/16 19:21
 */
@Repository
public class AutoReplyKeywordsInfoDaoImpl implements AutoReplyKeywordsInfoDao {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoUtil mongoUtil;

    @Override
    public List<AutoReplyKeywordsInfo> getListByAppId(String appId, int status) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(appId));
        query.with(new Sort(Sort.Direction.DESC, "createDate"));
        return mongoTemplate.find(query, AutoReplyKeywordsInfo.class);
    }

    @Override
    public void insert(AutoReplyKeywordsInfo autoReplyKeywordsInfo) {
        mongoTemplate.insert(autoReplyKeywordsInfo);
    }

    @Override
    public List<AutoReplyKeywordsInfo> getListByAppIdAndStatus(String appId, Integer status) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(appId).and("status").is(status));
        return mongoTemplate.find(query, AutoReplyKeywordsInfo.class);
    }

    @Override
    public long modifyStatus(String appId, String ruleId, Integer status) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(appId).and("status").is(status));
        Update update = new Update();
        update.set("status", status);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, AutoReplyKeywordsInfo.class);
        return updateResult.getModifiedCount();
    }

    @Override
    public long upsert(AutoReplyKeywordsInfo autoReplyKeywordsInfo) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(autoReplyKeywordsInfo.getId()));
        return mongoUtil.upsertOne(autoReplyKeywordsInfo, query, AutoReplyKeywordsInfo.class);
    }
}
